<?php namespace Phpcmf\Controllers;

class Order extends \Phpcmf\Home\Module {

	public function __construct(...$params) {
		parent::__construct(...$params);
        $this->_module_init();
        !$this->uid && exit($this->_msg(0, '你还没有登录'));
	}

	// 直接付款
	public function buy() {

        $id = (int)\Phpcmf\Service::L('input')->get('id');
        $fid = (int)\Phpcmf\Service::L('input')->get('fid');

        if (!$id) {
            exit($this->_msg(0, dr_lang('id参数不存在')));
        } elseif (!$fid) {
            exit($this->_msg(0, dr_lang('字段fid参数不存在')));
        }

        $num = max(1, (int)\Phpcmf\Service::L('input')->get('num'));
        $sku = dr_safe_replace(\Phpcmf\Service::L('input')->get('sku'), 'undefined');

        $field = $this->get_cache('table-field', $fid);
        if (!$field) {
            exit($this->_msg(0, dr_lang('支付字段[%s]不存在', $fid)));
        }

        // 获取订单最终价格和库存信息
        $rt = \Phpcmf\Service::M('order', 'store')->get_goods_info($id, $field, $num, $sku);
        if (isset($rt['code']) && !$rt['code']) {
            exit($this->_msg(0, $rt['msg']));
        } elseif (!$rt['quantity']) {
            exit($this->_msg(0, dr_lang('该商品已销售完')));
        } elseif ($rt['quantity'] < $num) {
            exit($this->_msg(0, dr_lang('该商品库存不足，商品剩余：%s', $rt['quantity'])));
        }

        // 获取模块id
        list($a, $b, $rid, $fid) = explode('-', $rt['mid']);
        list($s, $mid) = explode('_', $a);

        $list[] = $rt;

        $this->_checkout($mid, $list, $rt['total'], $rt['give_score'], $rt['give_money']);
    }

	// 购物车的确认结算
	public function checkout() {

        $id = (int)\Phpcmf\Service::L('input')->get('id');
        if (!$id) {
            exit($this->_msg(0, dr_lang('%s，请重新下单', '订单失效')));
        }

        $ocart = \Phpcmf\Service::M('Order', 'store')->my_order_cart_info($id);
        if (!$ocart) {
            exit($this->_msg(0, dr_lang('%s，请重新下单', '订单不存在')));
        }

        $cart = \Phpcmf\Service::M('Order', 'store')->my_cart_items(explode(',', $ocart['cid']));
        if (!$cart) {
            exit($this->_msg(0, dr_lang('%s，请重新下单', '无可用订单')));
        }

        $mid = [];
        $list = [];
        $total = $give_money = $give_score = 0;

        foreach ($cart as $t) {
            list($a, $rid, $fid) = explode('-', $t['mid']);
            list($s, $name) = explode('_', $a);
            $mid[$name] = $name;
            $field = $this->get_cache('table-field', $fid);
            if (!$field) {
                \Phpcmf\Service::M('Order', 'store')->delete_order_cart($id);
                exit($this->_msg(0, dr_lang('%s#%s，请重新下单', '支付字段不存在', $fid)));
            }

            // 获取订单最终价格和库存信息
            $rt = \Phpcmf\Service::M('order', 'store')->get_goods_info($rid, $field, $t['quantity'], $t['sku_value']);
            if (isset($rt['code']) && !$rt['code']) {
                \Phpcmf\Service::M('order', 'store')->delete_order_cart($id);
                exit($this->_msg(0, dr_lang('%s，请重新下单', $rt['msg'])));
            }

            if (!$rt['quantity']) {
                exit($this->_msg(0, dr_lang('该商品已销售完')));
            } elseif ($rt['quantity'] < $t['quantity']) {
                exit($this->_msg(0, dr_lang('该商品库存不足，商品剩余：%s', $rt['quantity'])));
            }

            $list[$t['id']] = $rt;
            $total+= $rt['total'];

            $give_money+= $rt['give_money'];
            $give_score+= $rt['give_score'];

        }

        if (count($mid) > 2) {
            exit($this->_msg(0, dr_lang('购物车中商品格式不正确')));
        }

        $this->_checkout(array_shift($mid), $list, $total, $give_score, $give_money, $ocart);
    }

    // 团购付款
    public function tuan() {

	    exit;
        $id = (int)\Phpcmf\Service::L('input')->get('id');
        $fid = (int)\Phpcmf\Service::L('input')->get('fid');

        !$id && exit($this->_msg(0, dr_lang('id参数不存在')));
        !$fid && exit($this->_msg(0, dr_lang('字段fid参数不存在')));

        $tuan = \Phpcmf\Service::M('tuan', 'tuan')->get_info($id);
        if (!$tuan) {
            $this->_msg(dr_lang('团购商品(id#%s)不存在', $id));
        } elseif (!$tuan['status']) {
            $this->_msg(dr_lang('团购商品(id#%s)已下架', $id));
        } elseif (SYS_TIME < $tuan['stime']) {
            $this->_msg(dr_lang('团购商品(id#%s)未开始', $id));
        } elseif (SYS_TIME > $tuan['etime']) {
            $this->_msg(dr_lang('团购商品(id#%s)已结束', $id));
        }

        $num = max(1, (int)\Phpcmf\Service::L('input')->get('num'));
        $sku = dr_safe_replace(\Phpcmf\Service::L('input')->get('sku'), 'undefined');

        $field = $this->get_cache('table-field', $fid);
        !$field && exit($this->_msg(0, dr_lang('支付字段不存在')));

        // 获取订单最终价格和库存信息
        $rt = \Phpcmf\Service::M('order', 'order')->get_tuan_goods_info($tuan['cid'], $field, $num, $sku, $tuan);
        isset($rt['code']) && !$rt['code'] && exit($this->_msg(0, $rt['msg']));
        !$rt['quantity'] && exit($this->_msg(0, dr_lang('该商品已销售完')));
        $rt['quantity'] < $num && exit($this->_msg(0, dr_lang('该商品库存不足，商品剩余：%s', $rt['quantity'])));

        // 获取模块id
        list($a, $b, $rid, $fid) = explode('-', $rt['mid']);
        list($s, $mid) = explode('_', $a);

        if ($tuan['xgs'] && \Phpcmf\Service::M('order', 'order')->xgs($mid, $tuan['xgs'])) {
            $this->_msg(dr_lang('团购商品(id#%s)购买次数达到上限', $id));
        }

        $list[] = $rt;

        $this->_checkout($mid, $list, $rt['total'], $rt['give_score'], $rt['give_money']);
    }

    // 组合付款
    public function merge() {


    }

    // 确认结算
    public function _checkout($mid, $list, $total, $give_score, $give_money, $ocart = []) {

        // 判断是否存在订单优惠
        $jian = 0;
        $discount = \Phpcmf\Service::M('order', 'store')->get_order_discount($total, $this->member);
        if ($discount) {
            $jian = $discount['jian'];
        }

        if (isset($_GET['is_ajax_get']) && $_GET['is_ajax_get']) {
            // ajax请求运费和总价
            $freight = \Phpcmf\Service::M('order', 'store')->get_freight_price((int)$_GET['city'], $list);
            $this->_json(1, '', ['total' => number_format($total + $freight - $jian, 2), 'freight' => number_format($freight, 2)]);
            exit;
        }

        // 可用优惠券
        $my_coupon = [];

        // 付款方式
        list($pay_type, $pay_default) = dr_store_order_get_pay_type();

        // 提交订单
        if (IS_POST) {
            // 收货地址
            if ($this->mall_info['order']['buy_address']) {
                $address = \Phpcmf\Service::M('Address', 'store')->info((int)\Phpcmf\Service::L('input')->post('address'));
                !$address && exit($this->_json(0, dr_lang('收货人信息不存在')));
                $address['address'] = dr_linkagepos(FC_ADDRESS_CITY, $address['city'], '', '').$address['address'];
            }
            // 付款方式
            $pay_name = \Phpcmf\Service::L('input')->post('paytype');
            if (!$pay_type[$pay_name]) {
                exit($this->_json(0, dr_lang('付款方式不存在')));
            }
            // 优惠券
            $coupon = (int)\Phpcmf\Service::L('input')->post('coupon');
            if ($coupon && isset($my_coupon[$coupon]) && $my_coupon[$coupon]) {
                // 重新获取优惠价格
                $jian += (float)$my_coupon[$coupon]['money'];
            }
            // 获取运费
            $freight = \Phpcmf\Service::M('order', 'store')->get_freight_price($address['city'], $list);
            // 计算付款价格
            $money = max(0, $total + $freight - $jian);
            // 免费订单余额支付
            floatval($money) == 0 && $pay_name = 'finecms';
            $order = [
                'sn' => dr_store_order_get_order_sn(),
                'money' => $money, //订单付款总金额
                'freight' => $freight, // 运费
                'discount' => $jian, // 优惠的金额
                'coupon' => $coupon, // 优惠卷id
                'give_score' => $give_score, // 赠送积分
                'give_money' => $give_money, // 赠送金额
                'promotion_name' => $discount ? $discount['title'] : '', // 订单折扣名称
                'promotion_info' => $discount ? $discount['info'] : '', // 定制折扣详情
                'source' => dr_store_order_get_agent_name(), // 来源
                'name' => $address ? $address['name'] : '',
                'email' => $this->member['email'],
                'phone' => $address ? $address['phone'] : '',
                'address' => $address ? $address['address'] : '',
                'pay_type' => $pay_name, // 付款方式
                'remark' => dr_safe_replace(\Phpcmf\Service::L('input')->post('remark')), // 订单备注
            ];
            $rt = \Phpcmf\Service::M('order', 'store')->checkout($order, $list, $ocart);
            if (!$rt['code']) {
                $this->_json(0, $rt['msg']);
            }
            // 下单成功，跳转支付
            exit($this->_json(
                1, dr_lang('下单成功，正在跳转支付页面'), [
                    'url' => dr_url('store/order/pay', ['id' => $rt['code']])
                ]
            ));
        }

        \Phpcmf\Service::V()->assign([
            'list' => $list,
            'pay_type' => $pay_type,
            'pay_default' => $pay_default,
            'discount' => $discount,
            'order_total' => $total,
            'pay_total' => $total - $jian,
            'give_score' => $give_score,
            'give_money' => $give_money,
            'is_address' => $this->mall_info['order']['buy_address'],
            'address' => $this->mall_info['order']['buy_address'] ? \Phpcmf\Service::M('address', 'store')->my_address() : [],
            'meta_title' => dr_lang('订单结算').SITE_SEOJOIN.SITE_NAME,
            'meta_keywords' => $this->get_cache('site', SITE_ID, 'config', 'SITE_KEYWORDS'),
            'meta_description' => $this->get_cache('site', SITE_ID, 'config', 'SITE_DESCRIPTION')
        ]);
        \Phpcmf\Service::V()->display('order_checkout.html');
    }

    // 订单付款
    public function pay() {

        if (!$this->uid) {
            exit($this->_msg(0, '你还没有登录'));
        }

        $id = (int)\Phpcmf\Service::L('input')->get('id');
        if (!$id) {
            exit($this->_msg(0, dr_lang('订单参数不存在')));
        }

        $order = \Phpcmf\Service::M('Order', 'store')->info($id);
        if (!$order) {
            exit($this->_msg(0, dr_lang('订单记录不存在')));
        } elseif ($order['uid'] != $this->uid) {
            exit($this->_msg(0, dr_lang('你无查看此订单')));
        }

        $money = floatval($order['money']);
        if ($money > 0) {
            // 创建支付
            $pay = [
                'mark' => 'my-store_buy-'.$order['id'],
                'sn' => $order['sn'],
                'uid' => $order['uid'],
                'username' => $order['username'],
                'type' => $order['pay_type'],
                'url' => \Phpcmf\Service::L('Router')->member_url('store/order/show', ['id' => $id]),
                'money' => $money,
            ];
            $rt = \Phpcmf\Service::M('Pay')->post($pay);
            if (!$rt['code']) {
                $this->_msg(0, $rt['msg']);exit;
            }
            // 跳转到支付页面
            $url = ROOT_URL.'index.php?s=api&c=pay&id='.$rt['code'];
            dr_redirect($url, 'auto');
            exit;
        } else {
            // 免费订单，直接标志付款
            \Phpcmf\Service::M('Order', 'store')->pay($this->uid, $id, 0);
            exit($this->_json(
                1, dr_lang('订单付款成功'), [
                    'url' => \Phpcmf\Service::L('Router')->member_url('store/order/show', ['id' => $id])
                ]
            ));
        }
    }

    // 添加或修改收货地址
    public function address() {

        if (!$this->uid) {
            exit($this->_json(0, dr_lang('登录之后在操作')));
        }

        $id = (int)\Phpcmf\Service::L('Input')->get('id');
        $data = \Phpcmf\Service::M('Address', 'store')->info($id);

        if (IS_POST) {
            $post = \Phpcmf\Service::L('Input')->post('data');
            if (!$post['name']) {
                $this->_json(0, dr_lang('姓名不能为空'), ['field' => 'name']);
            } elseif (!$post['city']) {
                $this->_json(0, dr_lang('请选择一个城市'), ['field' => 'city']);
            } elseif (!$post['address']) {
                $this->_json(0, dr_lang('详细地址不能为空'), ['field' => 'address']);
            } elseif (!$post['phone']) {
                $this->_json(0, dr_lang('手机号码不能为空'), ['field' => 'phone']);
            }
            $rt = \Phpcmf\Service::M('Address', 'store')->save_info($data['id'], $post);
            if (!$rt['code']) {
                $this->_json(0, $rt['msg']);
            } else {
                $this->_json(1, dr_lang('操作成功'), $rt['data']);
            }
        }

        \Phpcmf\Service::V()->assign([
            'city' => dr_fieldform(array(
                'ismain' => 1,
                'name' => dr_lang('城市'),
                'fieldname' => 'city',
                'fieldtype' => 'Linkage',
                'setting' => array(
                    'option' => array(
                        'linkage' => FC_ADDRESS_CITY,
                    ),
                )
            ), (int)$data['city']),
            'address' => $data,
        ]);
        \Phpcmf\Service::V()->display('order_address.html');
        exit;
    }
}
